//
//  ShareWarpper.m
//  YuiKe
//
//  Created by yuike5 yuike5 on 11-10-31.
//  Copyright 2011年 yuike. All rights reserved.
//

#import "ShareWarpper.h"
#import "ShareController.h"
#import "mcf.h"
#import "QQShare.h"

@implementation EmailAttachment
@synthesize data;
@synthesize fileName;
@synthesize mimeType;
-(void) dealloc
{
    YRelease(data)
    YRelease(fileName)
    YRelease(mimeType)
    [super dealloc];
}
@end

@implementation WeiboWarperNodex
@synthesize message;
@synthesize cpsUrlReal;
@synthesize cpsUrlShow;
@synthesize image;
@synthesize hideTextHead;
@synthesize hideTextTail;
@synthesize suggests;

@synthesize theNaviTitle;
@synthesize theTip;
@synthesize imageurl;

@synthesize product_title;
@synthesize product_url;
@synthesize product_summary;

-(id) init // default [WeiboBase rootNick];
{
    self = [super init];
    if (self) {
        self.hideTextTail = [WeiboBase rootNick];
    }
    return self;
}

-(void) dealloc 
{
    YRelease(message)
    YRelease(cpsUrlReal)
    YRelease(cpsUrlShow)
    
    YRelease(image)
    YRelease(hideTextHead)
    YRelease(hideTextTail)
    YRelease(suggests)
    
    YRelease(theNaviTitle)
    YRelease(theTip)
    YRelease(imageurl)
    
    YRelease(product_title)
    YRelease(product_url)
    YRelease(product_summary)
    [super dealloc];
}
@end

@implementation EmailWarperNodex
@synthesize title;
@synthesize html;
@synthesize attachments;
-(void) dealloc
{
    YRelease(title)
    YRelease(html)
    YRelease(attachments)
    [super dealloc];
}
@end

@implementation ImageWarperNodex
@synthesize coverImage;
@synthesize images;
-(void) dealloc
{
    YRelease(coverImage)
    YRelease(images)
    [super dealloc];
}
@end




@implementation ShareWarpper
@synthesize delegate;
@synthesize useCustomedActionSheet;

@synthesize SHARE_SINA_WEIBO;// @"分享到新浪微博"
@synthesize SHARE_EMAIL;// @"用邮件发送"
@synthesize SAVE_IMAGE;//  @"保存当前图片到相册"
@synthesize SAVE_IMAGES;// @"保存当前图集到相册"
@synthesize EMAIL_ACCOUNT_NOT_SETED;//@"邮件帐号未设置"

@synthesize SHARE_TENCENT_WEIBO;  // 分享到腾讯微博
@synthesize SHARE_TENCENT_SPACE;  // 分享到QQ空间说说
@synthesize SHARE_TENCENT_ALL;    // @"分享到QQ分享";//分享到QQ空间朋友网和腾讯微博
@synthesize SAVE_IMAGE_QQ_SPACE;  // 上传当前图片到QQ空间相册
@synthesize SAVE_IMAGES_QQ_SPACE; // 上传当前图集到QQ空间相册



-(void) setDoneDelegate:(id)delegatex sel:(SEL)sel
{
    doneDelegate = delegatex;
    doneSel = sel;
}


- (id)init:(UIViewController*)vCtrl_ delegate:(id<ShareWarpperDelegate>)delegate_
{
    self = [super init];
    if (self) {
        // Initialization code here.
        vCtrl = vCtrl_;
        delegate = delegate_;
//        imageArray = [[NSMutableArray alloc] init];
        
        self.SHARE_SINA_WEIBO= @"分享到新浪微博";
        self.SHARE_EMAIL= @"用邮件发送";
        self.SAVE_IMAGE = @"保存当前图片到相册";
        self.SAVE_IMAGES= @"保存当前图集到相册";
        self.EMAIL_ACCOUNT_NOT_SETED=@"邮件帐号未设置";
        
        self.SHARE_TENCENT_WEIBO = @"分享到腾讯微博";
        self.SHARE_TENCENT_SPACE = @"分享到QQ空间说说";
        self.SHARE_TENCENT_ALL =   @"分享到QQ分享";//@"分享到QQ空间朋友网和腾讯微博";
        self.SAVE_IMAGE_QQ_SPACE = @"上传当前图片到QQ空间相册";
        self.SAVE_IMAGES_QQ_SPACE= @"上传当前图集到QQ空间相册";
    }
    
    return self;
}

-(void) dealloc
{
    [SHARE_SINA_WEIBO release];
    [SHARE_EMAIL release];
    
    [SAVE_IMAGE release];
    [SAVE_IMAGES release];
    [EMAIL_ACCOUNT_NOT_SETED release];
    
    [SHARE_TENCENT_WEIBO release];
    [SHARE_TENCENT_SPACE release];
    [SHARE_TENCENT_ALL release];
    [SAVE_IMAGE_QQ_SPACE release];
    [SAVE_IMAGES_QQ_SPACE release];
//    [imageArray release];
    [super dealloc];
}





-(UIActionSheet*) ActionButtonActionSheet:(int)incx
{  
    UIActionSheet* actionButtonActionSheet = [[UIActionSheet alloc] initWithTitle:nil  
                                                                         delegate:self  
                                                                cancelButtonTitle:nil  
                                                           destructiveButtonTitle:nil  
                                                                otherButtonTitles:nil]; 
    if (incx & SHAREMASK_SINA_WEIBO) {
        [actionButtonActionSheet addButtonWithTitle:SHARE_SINA_WEIBO];
    }
    
    if (incx & SHAREMASK_TENCENT_SHARE) {
//        [actionButtonActionSheet addButtonWithTitle:SHARE_TENCENT_WEIBO];
    }
    
    if (incx & SHAREMASK_EMAIL) {
        [actionButtonActionSheet addButtonWithTitle:SHARE_EMAIL];
    }
    if (incx & SHAREMASK_SAVE_IMAGE) {
        [actionButtonActionSheet addButtonWithTitle:SAVE_IMAGE];
        [actionButtonActionSheet addButtonWithTitle:SAVE_IMAGES];
    }
    
    if (incx & SHAREMASK_TENCENT_SHARE) {
//        [actionButtonActionSheet addButtonWithTitle:SHARE_TENCENT_SPACE];
        [actionButtonActionSheet addButtonWithTitle:SHARE_TENCENT_ALL];
    }
    
    if (incx & SHAREMASK_SAVE_IMAGE) {
//        [actionButtonActionSheet addButtonWithTitle:SAVE_IMAGE_QQ_SPACE];
//        [actionButtonActionSheet addButtonWithTitle:SAVE_IMAGES_QQ_SPACE];
    }
    return [actionButtonActionSheet autorelease];
}

-(MyActionSheet*) MyActionButtonActionSheet:(int)incx
{  
    MyActionSheet* actionButtonActionSheet = [[MyActionSheet alloc] initWithDelegate:self  
                                                                        buttonTitles:nil]; 
    if (incx & SHAREMASK_SINA_WEIBO) {
        [actionButtonActionSheet addButtonWithTitle:SHARE_SINA_WEIBO];
    }
    
    if (incx & SHAREMASK_TENCENT_SHARE) {
//        [actionButtonActionSheet addButtonWithTitle:SHARE_TENCENT_WEIBO];
    }
    
    if (incx & SHAREMASK_EMAIL) {
        [actionButtonActionSheet addButtonWithTitle:SHARE_EMAIL];
    }
    if (incx & SHAREMASK_SAVE_IMAGE) {
        [actionButtonActionSheet addButtonWithTitle:SAVE_IMAGE];
        [actionButtonActionSheet addButtonWithTitle:SAVE_IMAGES];
    }
    
    if (incx & SHAREMASK_TENCENT_SHARE) {
//        [actionButtonActionSheet addButtonWithTitle:SHARE_TENCENT_SPACE];
        [actionButtonActionSheet addButtonWithTitle:SHARE_TENCENT_ALL];
    }
    
    if (incx & SHAREMASK_SAVE_IMAGE) {
//        [actionButtonActionSheet addButtonWithTitle:SAVE_IMAGE_QQ_SPACE];
//        [actionButtonActionSheet addButtonWithTitle:SAVE_IMAGES_QQ_SPACE];
    }
    return [actionButtonActionSheet autorelease];
}




-(void) shareItemPressedItem:(UIBarButtonItem*) item  idx:(ShareId)idx with:(int)incx
{
    thisidx = idx;
    UIActionSheet* actionButtonActionSheet = [self ActionButtonActionSheet:incx]; 
    
    int num = [actionButtonActionSheet numberOfButtons];
    if (num == 0) {
        return;
    } else if (num == 1) {
        [self actionSheet:actionButtonActionSheet clickedButtonAtIndex:0];
    } else {
        [actionButtonActionSheet showFromBarButtonItem:item animated:YES];
    }
}
-(void) shareItemPressedRect:(CGRect)rect view:(UIView*)view  idx:(ShareId)idx with:(int)incx
{
    if (!useCustomedActionSheet) {
        thisidx = idx;
        UIActionSheet* actionButtonActionSheet = [self ActionButtonActionSheet:incx]; 
        int num = [actionButtonActionSheet numberOfButtons];
        if (num == 0) {
            return;
        } else if (num == 1) {
            [self actionSheet:actionButtonActionSheet clickedButtonAtIndex:0];
        } else {
            
            // share pointer
            if (rect.size.width > 30) {        
                rect.origin.x += (rect.size.width/2-10);
                rect.size.width -= (rect.size.width/2-10)*2;
            }
            if (rect.size.height > 30) {
                rect.origin.y += (rect.size.height/2-10);
                rect.size.height -= (rect.size.height/2-10)*2;
            }
            [actionButtonActionSheet showFromRect:rect inView:view animated:YES];
        }
        
        
    } else {
        thisidx = idx;
        MyActionSheet* actionButtonActionSheet = [self MyActionButtonActionSheet:incx]; 
        int num = [actionButtonActionSheet numberOfButtons];
        if (num == 0) {
            return;
        } else if (num == 1) {
            [self myActionSheet:actionButtonActionSheet clickedButtonAtIndex:0 title:[actionButtonActionSheet buttonTitleAtIndex:0]];
        } else {
        
            // share pointer
            if (rect.size.width > 30) {        
                rect.origin.x += (rect.size.width/2-10);
                rect.size.width -= (rect.size.width/2-10)*2;
            }
            if (rect.size.height > 30) {
                rect.origin.y += (rect.size.height/2-10);
                rect.size.height -= (rect.size.height/2-10)*2;
            }
            [actionButtonActionSheet showFromRect:rect inView:view animated:YES];
        }
    }
}

-(void) commentItemPressed:(WeiboBase*)weibo node:(WeiboNode*)node callback:(id<CommentControllerCallback>)callback  idx:(ShareId)idx
{
    thisidx = idx;
    CommentController* share = [[CommentController alloc] initWithStyle:UITableViewStyleGrouped];
    [share setCallback:callback];
    //[share setDoneDelegate:doneDelegate sel:doneSel];
    [share autorelease];
    
    [share setWeibo:[weibo theSnsId] node:node];
    if (self.delegate && [self.delegate performSelector:@selector(shareWarperWeiboSuggests:)]) {
        [share setWeiboSuggests: [self.delegate shareWarperWeiboSuggests: idx]];
    }
    
    
    UINavigationController* navi = [[UINavigationController alloc] initWithRootViewController:share];
    [navi autorelease];
    
    navi.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
    navi.modalPresentationStyle = UIModalPresentationFormSheet;
    [vCtrl presentModalViewController:navi animated:YES];
}




- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{   
    if (buttonIndex < 0) {
        return;
    }
    NSString* title = [actionSheet buttonTitleAtIndex:buttonIndex];
    [self actionTitle:title];
}
// Called when a button is clicked. The view will be automatically dismissed after this call returns
- (void)myActionSheet:(MyActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex  title:(NSString*)title {
    if (buttonIndex < 0) {
        return;
    }
    [self actionTitle:title];
}

// Called when we cancel a view (eg. the user clicks the Home button). This is not called when the user clicks the cancel button.
// If not defined in the delegate, we simulate a click in the cancel button
- (void)myActionSheetCancel:(MyActionSheet *)actionSheet {

}


- (void)actionTitle:(NSString*)title
{
    if ([title compare:SHARE_TENCENT_ALL] == 0 || [title compare:SHARE_SINA_WEIBO] == 0) {
        
        WeiboBase* sinaweibo = nil;
        if ([title compare:SHARE_SINA_WEIBO] == 0)
            sinaweibo = [[[SinaWeibo alloc] init] autorelease];  
        if ([title compare:SHARE_TENCENT_ALL] == 0)
            sinaweibo = [[[QQShare alloc] init ] autorelease];
        if (sinaweibo == nil)
            return;
        
        ShareController* share = [[ShareController alloc] initWithStyle:UITableViewStyleGrouped andWeiboBase:sinaweibo];
        [share setDoneDelegate:doneDelegate sel:doneSel];
        WeiboWarperNodex* nodex = [delegate shareWarperWeibo:thisidx];
        
        [share setWeiboImage: nodex.image];
        [share setWeiboText: nodex.message];
        [share setWeiboCpsUrlShow:nodex.cpsUrlShow andReal:nodex.cpsUrlReal];
        share.weibo_hide_text_head = nodex.hideTextHead;
        share.weibo_hide_text_tail = nodex.hideTextTail;
        [share setWeiboSuggests: nodex.suggests];
        share.titleForFooterInSection = nodex.theTip;
        share.product_title = nodex.product_title;
        share.product_url = nodex.product_url;
        share.product_summary = nodex.product_summary;
        share.imageurl = nodex.imageurl;
        [share autorelease];
        
        if (nodex.theNaviTitle) {
            share.title = [NSString stringWithFormat:@"%@·%@", nodex.theNaviTitle, sinaweibo.title];
        } else {
            share.title = [NSString stringWithFormat:@"%@·%@", @"分享", sinaweibo.title];
        }
        UINavigationController* navi = [[UINavigationController alloc] initWithRootViewController:share];
        [navi autorelease];        
        navi.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
        navi.modalPresentationStyle = UIModalPresentationFormSheet;
        [vCtrl presentModalViewController:navi animated:YES];
    }
    if ([title compare:SHARE_EMAIL] == 0) {
        
        EmailWarperNodex* nodex = [delegate shareWarperEmail:thisidx];
        
        NSString* subject = nodex.title;
        NSString* body = nodex.html;
        NSArray* objs = nodex.attachments;
        
        [self sendEmailTitle:subject body:body toaddr:nil objs:objs];
    }
    
    if ([title compare:SAVE_IMAGE] == 0) {
        [self performSelector:@selector(menuItemSaveImageAlbum) withObject:nil afterDelay:0.1f];
    }
    
    
    if ([title compare:SAVE_IMAGES] == 0) {
        [self performSelector:@selector(menuItemSaveImageAlbumArray) withObject:nil afterDelay:0.1f];
    }
    
}


//================ 菜单动作 ======== BEGIN
#define HUD_TAG 2344545
-(void) menuItemSaveImageAlbum
{
    MBProgressHUD* hud = [MBProgressHUD showHUDAddedTo:vCtrl.view animated:YES];
    hud.labelText = @"图片保存中";
    hud.tag = HUD_TAG;
    
    UIImage* image = [delegate shareWarperImage:thisidx].coverImage;
    UIImageWriteToSavedPhotosAlbum(image, self, @selector(image:didFinishSavingWithError:contextInfo:), nil);
}
- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo
{
    MBProgressHUD* hud = (MBProgressHUD *) [vCtrl.view viewWithTag:HUD_TAG];
    if (error == nil) {
        hud.customView = [[[UIImageView alloc] initWithImage: [UIImage imageNamed:@"37x37-Checkmark.png"]] autorelease];
        hud.mode = MBProgressHUDModeCustomView; // 必须 在hud.customView后面 设置。。
        hud.labelText = @"图片已保存";        
        hud.removeFromSuperViewOnHide = YES;
        [hud hide:YES afterDelay:1.0f];
    } else {
        hud.customView = [[[UIImageView alloc] initWithImage: [UIImage imageNamed:@"37x37-Exclamationmark.png"]] autorelease];
        hud.mode = MBProgressHUDModeCustomView; // 必须 在hud.customView后面 设置。。
        hud.labelText = @"图片保存失败";        
        hud.removeFromSuperViewOnHide = YES;
        [hud hide:YES afterDelay:1.5f];
    }
    
//    NSString* msg = [error localizedFailureReason];
//    msg = [error localizedDescription];
//    msg = nil;
}



-(void) trySaveArrayNextImage
{
    if (imageSaveCount==0) return; // 避免显示hud。。。

    MBProgressHUD* hud = nil;
    if (imageSaveIndex >= imageSaveCount) { // compleated...
        hud = (MBProgressHUD *) [vCtrl.view viewWithTag:HUD_TAG];
        hud.progress = 1.0f;
        
        dispatch_async(dispatch_get_global_queue( DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
            // Do a taks in the background
            sleep(0.5f); // 显示完成。。。
            // Hide the HUD in the main tread 
            dispatch_async(dispatch_get_main_queue(), ^{
                if (imageSaveFailCount==0) {
                    hud.customView = [[[UIImageView alloc] initWithImage: [UIImage imageNamed:@"37x37-Checkmark.png"]] autorelease];
                    hud.mode = MBProgressHUDModeCustomView; // 必须 在hud.customView后面 设置。。
                    hud.labelText = [NSString stringWithFormat:@"保存成功 %d 张", imageSaveOkCount];
                    hud.removeFromSuperViewOnHide = YES;
                    [hud hide:YES afterDelay:1.0f];
                } else {
                    hud.customView = [[[UIImageView alloc] initWithImage: [UIImage imageNamed:@"37x37-Exclamationmark.png"]] autorelease];
                    hud.mode = MBProgressHUDModeCustomView; // 必须 在hud.customView后面 设置。。
                    hud.labelText = [NSString stringWithFormat:@"成功保存 %d 张，失败 %d 张", imageSaveOkCount, imageSaveFailCount];
                    hud.removeFromSuperViewOnHide = YES;
                    [hud hide:YES afterDelay:1.5f];
                }
            });
        });
        return;
    }
    
    if (imageSaveIndex == 0) {
        hud = [MBProgressHUD showHUDAddedTo:vCtrl.view animated:YES];
        hud.mode = MBProgressHUDModeDeterminatex;
        hud.labelText = @"图集保存中";
        hud.tag = HUD_TAG;
    } else {
        hud = (MBProgressHUD *) [vCtrl.view viewWithTag:HUD_TAG];
    }
    hud.progress = imageSaveIndex * 1.0 / imageSaveCount;
    
    
    NSArray* images = [delegate shareWarperImage:thisidx].images;
    UIImage* image = imageSaveIndex<images.count?[images objectAtIndex:imageSaveIndex]:nil;
    imageSaveIndex++;
    UIImageWriteToSavedPhotosAlbum(image, self, @selector(imageArray:didFinishSavingWithError:contextInfo:), nil);
}
-(void) menuItemSaveImageAlbumArray
{
    imageSaveOkCount = imageSaveFailCount = 0;
    imageSaveCount = [delegate shareWarperImage:thisidx].images.count;
    imageSaveIndex = 0;
    [self trySaveArrayNextImage];
}
- (void)imageArray:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo
{
    if (error == nil)
        imageSaveOkCount++;
    else {
        imageSaveFailCount++;
        
//        NSString* msg = [error localizedFailureReason];
//        msg = [error localizedDescription];
//        msg = nil;
    }    
    [self trySaveArrayNextImage];
}
//================ 菜单动作 ======== END







- (void)mailComposeController:(MFMailComposeViewController*)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError*)error 
{    
    switch (result) {
        case MFMailComposeResultCancelled:
        case MFMailComposeResultSaved:
        case MFMailComposeResultSent:
            [vCtrl becomeFirstResponder];
            [vCtrl dismissModalViewControllerAnimated:YES];
            break;
            
        case MFMailComposeResultFailed:
            [controller.view makeToast:@"邮件发送失败"];
//            NSString* msg = [error localizedFailureReason];
//            msg = [error localizedDescription];
//            msg = nil;
            break;
            
        default:
            break;
    }    
}


- (id)initEmail:(UIViewController*)vCtrl_
{
    return [self init:vCtrl_ delegate:nil];
}
- (BOOL)sendEmailTitle:(NSString*)title body:(NSString*)message toaddr:(NSString*)toaddr
{ 
    return [self sendEmailTitle:title body:message toaddr:toaddr objs:nil];
}


- (BOOL)sendEmailTitle:(NSString*)title body:(NSString*)message toaddr:(NSString*)toaddr objs:(NSArray*)objs
{
    if (![MFMailComposeViewController canSendMail]) {
        [vCtrl.view makeToast:EMAIL_ACCOUNT_NOT_SETED duration:TOAST_DRRATION_MIDDLE position:TOAST_POSITION_CENTER];
        return NO;    
    }
    
    MFMailComposeViewController *controller = [[MFMailComposeViewController alloc] init];
    //controller.modalPresentationStyle = UIModalPresentationFormSheet;
    controller.mailComposeDelegate = self;
    [controller setSubject: title];
    [controller setMessageBody: message isHTML:YES];
    if (toaddr != nil)
        [controller setToRecipients: [NSArray arrayWithObject:toaddr]];
    if (objs != nil) {
        for (NSObject* _obj in objs) {
            assert([_obj isKindOfClass:[EmailAttachment class]]); // assert.
            EmailAttachment* obj = (EmailAttachment*) _obj;
            [controller addAttachmentData:obj.data mimeType:obj.mimeType fileName:obj.fileName];
        }
    }
    [vCtrl presentModalViewController:controller animated:YES];
    [controller release];
    return YES;
}

@end
